<template>
  <el-row :gutter="20" id="adminUserPage">
    <!-- 查询表单 -->
    <el-col :span="4" :offset="0" id="adminUserPageForm">
      <el-form :model="userRequestForm" label-width="90px">
        <div id="adminUserPageFormTitleWrapper">
          <div>查询条件</div>
        </div>
        <el-form-item label="用户 id" prop="id">
          <el-input v-model="userRequestForm.id" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="用户账号" prop="userAccount">
          <el-input v-model="userRequestForm.userAccount" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="userName">
          <el-input v-model="userRequestForm.userName" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="用户简介" prop="userProfile">
          <el-input v-model="userRequestForm.userProfile" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="用户角色" prop="userRole">
          <el-select v-model="userRequestForm.userRole" placeholder="无限制">
            <el-option label="无限制" value=""></el-option>
            <el-option v-for="userRoleName in userRoleNameForRequest"
              :label="UserRoleEnumMap[userRoleName as keyof typeof UserRoleEnumMap]"
              :value="UserRoleEnum[userRoleName as keyof typeof UserRoleEnum]">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序字段" prop="sortField">
          <el-select v-model="userRequestForm.sortField" placeholder="无限制">
            <el-option
              v-for="validSortField in Object.keys(ValidSortFieldEnum).filter(key => Number.isNaN(Number(key)))"
              :label="ValidSortFieldEnumMap[validSortField as keyof typeof ValidSortFieldEnumMap]"
              :value="ValidSortFieldEnum[validSortField as keyof typeof ValidSortFieldEnum]">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序顺序" prop="sortOrder">
          <el-select v-model="userRequestForm.sortOrder" placeholder="无限制">
            <el-option label="升序" :value="SqlSortOrderEnum.ASC"></el-option>
            <el-option label="降序" :value="SqlSortOrderEnum.DESC"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <el-button type="primary" size="default" @click="doSearch" :loading="isLoading">查询</el-button>
    </el-col>

    <!-- 查询结果表格 -->
    <el-col :span="20" :offset="0" id="adminUserPageTable">
      <!-- 分页 -->
      <el-pagination @size-change="onSizeChange" @current-change="doSearch" v-model:currentPage="userRequestForm.current"
        :page-sizes="[5, 10, 15, 20]" :page-size="userRequestForm.pageSize" layout="total, sizes, prev, pager, next"
        :total="totalNum" background :pager-count="9" :disabled="paginationDisabled">
      </el-pagination>

      <el-table stripe :data="tableData" height="78vh" v-loading="isLoading">
        <el-table-column width="200" show-overflow-tooltip fixed="left" prop="id" label="用户 id" />
        <el-table-column show-overflow-tooltip prop="userAccount" label="用户账号" />
        <el-table-column show-overflow-tooltip prop="userName" label="用户昵称" />
        <el-table-column show-overflow-tooltip prop="userAvatar" label="用户头像">
          <template #default="scope">
            <template v-if="scope.row.userAvatar">
              <el-avatar :src="scope.row.userAvatar" style="width: 32px; height: 32px;" />
            </template>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="userProfile" label="用户简介" />
        <el-table-column show-overflow-tooltip prop="userRole" label="用户角色">
          <template #default="scope">
            {{ UserRoleEnumMap[UserRoleEnum[scope.row.userRole] as keyof typeof UserRoleEnumMap] }}
          </template>
        </el-table-column>
        <el-table-column width="180" show-overflow-tooltip prop="createTime" label="创建时间" />
        <el-table-column width="180" show-overflow-tooltip prop="updateTime" label="信息更新时间" />
        <el-table-column width="100" fixed="right" label="操作">
          <template #default="scope">
            <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { ResponseCodeEnum, SqlSortOrderEnum, UserRoleEnum, UserRoleEnumMap, ValidSortFieldEnum, ValidSortFieldEnumMap } from '@/enums';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';
import { deleteUserUsingDelete, listUserByPageUsingPost } from '@/api/userController';
import { Delete } from '@element-plus/icons-vue';

// 表单查询请求数据
const userRequestForm = ref<API.UserQueryRequest>({
  id: undefined,
  userAccount: '',
  userName: '',
  userProfile: '',
  userRole: '',
  current: 1,
  pageSize: 10,
  sortField: ValidSortFieldEnum.createTime,
  sortOrder: SqlSortOrderEnum.DESC,
});

// 筛选一下可用于查询的用户角色
const userRoleNameForRequest = Object.keys(UserRoleEnum).filter(key => Number.isNaN(Number(key))).filter(key => key !== 'NOT_LOGIN');

// 查询结果
const tableData = ref<API.User[]>([]);

// 查询总数
const totalNum = ref(0);

// 查询按钮是否正在加载中
const isLoading = ref(false);

// 分页插件是否可用
const paginationDisabled = ref(true);

/**
 * 当一页的数据量改变时触发
 * @param pageSize 当前一页容量
 */
const onSizeChange = (pageSize: number) => {
  userRequestForm.value.pageSize = pageSize;
  userRequestForm.value.current = 1;
  doSearch();
}

/**
 * 执行查询
 */
const doSearch = async () => {
  // 点过一次查询按钮后, 才启用分页插件
  paginationDisabled.value = false;

  isLoading.value = true;
  const result = await listUserByPageUsingPost(userRequestForm.value);
  isLoading.value = false;

  if (result.data.code === ResponseCodeEnum.SUCCESS) {
    // 更新表单数据与总数
    tableData.value = result.data.data?.records || [];
    totalNum.value = Number(result.data.data?.total) || 0;
  } else {
    ElMessage.error("获取数据失败: " + result.data.message);
  }
}

/**
 * 删除用户
 * @param index 所在行号
 * @param row 所在行数据
 */
const handleDelete = (index: number, row: API.User) => {
  ElMessageBox.confirm(
    '此操作将删除该用户, 是否继续 ?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const result = await deleteUserUsingDelete({
      id: row.id
    })

    if (result.data.code === ResponseCodeEnum.SUCCESS) {
      ElMessage.success(`成功删除 id = ${row.id} 的用户`);
      doSearch();
    } else {
      ElMessage.error("删除失败: " + result.data.message);
    }
  }).catch(() => { })
}

// 上来先查一次
onMounted(() => {
  doSearch();
})
</script>

<style scoped lang="less">
#adminUserPage {
  height: 100%;
  width: 100%;
}

#adminUserPageForm {
  border-right: 1px solid rgb(220, 223, 230);

  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: left;
  align-items: center;

  .el-button {
    width: 90%;
  }
}

#adminUserPageFormTitleWrapper {
  height: 6vh;
  display: flex;
  justify-content: center;
  align-items: center;

  div {
    font-size: 1.5rem;
  }
}

#adminUserPageTable {
  overflow: hidden;

  .el-pagination {
    margin: 10px 0;
  }
}
</style>